#include "ClipPlayer.h"
#include "QRScanner.h"
#include "ClipManager.h"
#include <dshow.h>

bool gScanning = false;
QRScanner gScanner = QRScanner::getInstance();
ClipManager gClipMgr = ClipManager::getInstance();
ClipPlayer* pPlayer = new ClipPlayer();

void newClipCallback(CLIP_TYPE prevType, CLIP_TYPE newType)
{
	if(prevType == TYPE_MAIN && newType == TYPE_IDLE)
	{
		gScanning = true;
		gScanner.showScanner();
	}
}

void clipStackEmptyCallback(void)
{
	Clip* pClip = gClipMgr.retrieveIdleClip();
	pPlayer->pushClip(pClip,false);
}

int __stdcall wWinMain(HINSTANCE hInstC, HINSTANCE hInstP, LPWSTR lpCmdLine, int nCmdShow)
{
	gClipMgr.loadFromFile("..\\clips.xml");

	gScanning = false;
	pPlayer->initialise(hInstC);

	gScanner.initialise();

	pPlayer->pushClip(gClipMgr.retrieveClip("intro",TYPE_MAIN),true);
	if(pPlayer->beginPlayback(gClipMgr.getVideoFilename()))
	{
		pPlayer->setNewClipCallback(newClipCallback);
		pPlayer->setClipStackEmptyCallback(clipStackEmptyCallback);

		MSG msg;
		bool running = true;
		while(running)
		{
			if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
			{
				if(msg.message == WM_QUIT || msg.message == WM_CLOSE)
				{
					running = false;
				}
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			gScanner.update();
			if(gScanning)
			{
				const char* buf = gScanner.scan();
				if(buf != NULL)
				{
					Clip* pClip = gClipMgr.retrieveClip(std::string(buf),TYPE_MAIN);
					if(!pClip)
					{
						pClip = gClipMgr.retrieveClip("unknown",TYPE_MAIN);
					}
					
					gScanning = false;
					gScanner.hideScanner();
					pPlayer->pushClip(pClip,true);
				}
			}

			pPlayer->update();
		}
	}

	gScanner.destroy();
	pPlayer->destroy();
	delete pPlayer;

	return 0;
}